import API_CONFIG, { buildApiUrl } from '@/config/api';

// HTTP请求工具类
class HttpClient {
  constructor() {
    this.baseURL = API_CONFIG.BASE_URL;
    this.timeout = API_CONFIG.TIMEOUT;
    this.defaultHeaders = { ...API_CONFIG.DEFAULT_HEADERS };
  }

  // 获取认证token
  getAuthToken() {
    return localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
  }

  // 获取刷新token
  getRefreshToken() {
    return localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken');
  }

  // 检查token是否过期
  isTokenExpired() {
    const expires = localStorage.getItem('tokenExpires') || sessionStorage.getItem('tokenExpires');
    if (!expires) return true;
    
    return Date.now() >= parseInt(expires);
  }

  // 刷新token
  async refreshAuthToken() {
    const refreshToken = this.getRefreshToken();
    if (!refreshToken) {
      throw new Error('No refresh token available');
    }

    try {
      const response = await fetch(buildApiUrl('/authority/refresh'), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ refreshToken })
      });

      if (!response.ok) {
        throw new Error('Token refresh failed');
      }

      const data = await response.json();
      
      if (data.code === "200" && data.data) {
        const { accessToken, refreshToken: newRefreshToken, expires } = data.data;
        
        // 更新存储的token
        const storage = localStorage.getItem('authToken') ? localStorage : sessionStorage;
        storage.setItem('authToken', accessToken);
        storage.setItem('refreshToken', newRefreshToken);
        storage.setItem('tokenExpires', expires.toString());
        
        return accessToken;
      } else {
        throw new Error('Invalid refresh response');
      }
    } catch (error) {
      // 刷新失败，清除所有认证信息
      this.clearAuthData();
      throw error;
    }
  }

  // 清除认证数据
  clearAuthData() {
    localStorage.removeItem('authToken');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('tokenExpires');
    localStorage.removeItem('userInfo');
    sessionStorage.removeItem('authToken');
    sessionStorage.removeItem('refreshToken');
    sessionStorage.removeItem('tokenExpires');
    sessionStorage.removeItem('userInfo');
  }

  // 构建请求头
  async buildHeaders(customHeaders = {}) {
    const headers = { ...this.defaultHeaders, ...customHeaders };
    
    // 添加认证头
    let token = this.getAuthToken();
    
    // 检查token是否过期，如果过期则尝试刷新
    if (token && this.isTokenExpired()) {
      try {
        token = await this.refreshAuthToken();
      } catch (error) {
        console.warn('Token refresh failed:', error);
        // 刷新失败，跳转到登录页
        if (window.location.hash !== '#/authority/login') {
          window.location.hash = '#/authority/login';
        }
        return headers;
      }
    }
    
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    return headers;
  }

  // 处理响应
  async handleResponse(response) {
    if (!response.ok) {
      const error = new Error(`HTTP Error: ${response.status}`);
      error.status = response.status;
      error.statusText = response.statusText;
      
      try {
        const errorData = await response.json();
        error.data = errorData;
        
        // 如果是401错误，可能是token过期
        if (response.status === 401) {
          this.clearAuthData();
          if (window.location.hash !== '#/authority/login') {
            window.location.hash = '#/authority/login';
          }
        }
      } catch (e) {
        // 如果响应不是JSON格式，忽略错误
      }
      
      throw error;
    }
    
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      return await response.json();
    }
    
    return await response.text();
  }

  // 通用请求方法
  async request(path, options = {}) {
    const url = buildApiUrl(path);
    const headers = await this.buildHeaders(options.headers);
    
    const config = {
      method: 'GET',
      headers,
      ...options,
    };

    // 处理请求体
    if (config.body && typeof config.body === 'object' && !(config.body instanceof FormData)) {
      config.body = JSON.stringify(config.body);
    }

    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), this.timeout);
      
      config.signal = controller.signal;
      
      const response = await fetch(url, config);
      clearTimeout(timeoutId);
      
      return await this.handleResponse(response);
    } catch (error) {
      if (error.name === 'AbortError') {
        throw new Error('请求超时');
      }
      throw error;
    }
  }

  // GET请求
  async get(path, params = {}, options = {}) {
    const url = new URL(path, 'http://localhost');
    
    // 添加查询参数
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null) {
        url.searchParams.append(key, params[key]);
      }
    });
    
    return await this.request(url.pathname + url.search, {
      method: 'GET',
      ...options,
    });
  }

  // POST请求
  async post(path, data = {}, options = {}) {
    return await this.request(path, {
      method: 'POST',
      body: data,
      ...options,
    });
  }

  // PUT请求
  async put(path, data = {}, options = {}) {
    return await this.request(path, {
      method: 'PUT',
      body: data,
      ...options,
    });
  }

  // DELETE请求
  async delete(path, options = {}) {
    return await this.request(path, {
      method: 'DELETE',
      ...options,
    });
  }

  // PATCH请求
  async patch(path, data = {}, options = {}) {
    return await this.request(path, {
      method: 'PATCH',
      body: data,
      ...options,
    });
  }

  // 文件上传
  async upload(path, file, options = {}) {
    const formData = new FormData();
    formData.append('file', file);
    
    // 添加额外的表单数据
    if (options.data) {
      Object.keys(options.data).forEach(key => {
        formData.append(key, options.data[key]);
      });
    }
    
    return await this.request(path, {
      method: 'POST',
      body: formData,
      headers: {
        // 不设置Content-Type，让浏览器自动设置multipart/form-data边界
        ...options.headers,
      },
    });
  }
}

// 创建全局HTTP客户端实例
export const http = new HttpClient();

// 导出类以便创建新实例
export default HttpClient;
